<?php
namespace Common\Model;
use Think\Model;

class PrivilegeModel extends  Model {
    protected $_validate = array(
        array('pri_name','require','权限名称不能为空！'), //默认情况下用正则进行验证
        array('pri_name','','权限名称已经存在！',0,'unique',1), // 在新增的时候验证name字段是否唯一
    );

    public function priTree()
    {
        $data=$this->select();
        return $this->resort($data);
    }

    public function resort($data,$pid=0,$level=0)
    {
        static $ret=array();
        foreach ($data as $k => $v)
        {
            if($v['pid']==$pid)
            {
                $v['level']=$level;
                $ret[]=$v;
                $this->resort($data,$v['id'],$level+1);
            }
        }

        return $ret;
    }
  public function childid($cateid)
    {
        $data=$this->select();
        return $this->getchildid($data,$cateid);
    }

    public function getchildid($data,$parentid)
    {
        static $ret=array();
        foreach ($data as $k=>$v) {
            if($v['parentid']==$parentid)
            {
                $ret[]=$v['id'];
                $this->getchildid($data,$v['id']);
            }
        }

        return $ret;
    }


    public function _before_delete($options)
    {

        //单独删除时候id的值，是一个字符串，是一个单独的id
        //$options['where']['id']    int(5)
        if (is_array($options['where']['id'])) {

            $arr = explode(',', $options['where']['id'][1]);
            $soncates = array(); 
            foreach ($arr as $k => $v) {
                $soncates2 = $this->childid($v);
                $soncates = array_merge($soncates, $soncates2);
            }
       
            $soncates = array_unique($soncates);
            $chilrenids = implode(',', $soncates);

        } else {
            $chilrenids = $this->childid($options['where']['id']); 
            $chilrenids = implode(',', $chilrenids);

        }

        if ($chilrenids) {
            $this->execute("delete from shop_privilege where id in($chilrenids)");
        }
    }

}